﻿using System.IO;
using System.Text;

namespace HelpTools.Helpers
{
    /// <summary>
    /// 文件操作帮助类
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file"></param>
        public static void DeleteFile(string file)
        {
            //去除文件夹和子文件的只读属性
            //去除文件夹的只读属性
            DirectoryInfo fileInfo = new DirectoryInfo(file);
            fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
            //去除文件的只读属性
            File.SetAttributes(file, FileAttributes.Normal);
            //判断文件夹是否还存在
            if (Directory.Exists(file))
            {
                foreach (string f in Directory.GetFileSystemEntries(file))
                {
                    if (File.Exists(f))
                    {
                        //如果有子文件删除文件
                        File.Delete(f);
                    }
                    else
                    {
                        //循环递归删除子文件夹 
                        DeleteFile(f);
                    }
                }
                //删除空文件夹 
                Directory.Delete(file);
            }
        }

        /// <summary>
        /// 读取文件信息
        /// </summary>
        /// <returns></returns>
        public static string ReadFile(string path)
        {
            var result = string.Empty;
            if (File.Exists(path))
            {
                using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        public static void SaveFile(string fileDir, string filePath, string content)
        {
            if (!Directory.Exists(fileDir))
                Directory.CreateDirectory(fileDir);
            if (File.Exists(filePath) == false)
            {
                using (File.Create(filePath)) { }
            }
            using (FileStream fs = File.OpenWrite(filePath))
            {
                using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
                {
                    writer.WriteLine(content);
                }
            }
        }
    }
}
